#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
from hashlib import sha1
import os, time
import re


class IPField(object):
    regular = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$"

    def __init__(self, required=True):
        self._required = required

    def valid(self, name, value):
        if not self._required:
            return value
        else:
            ret = re.match(IPField.regular, value)
            if not ret:
                raise Exception('%s Illegal' % name)
            return ret.group()



class MainForm(object):
    def __init__(self):
        self.ip = IPField(required=False)
        self.new_ip = IPField(required=True)

    def check_valid(self, request):
        is_success = True
        form_dict = self.__dict__
        for key, regular in form_dict.items():
            try:
                post_value = request.get_argument(key)
                # 让提交的数据 和 定义的正则表达式进行匹配
                result = regular.valid(key, post_value)
            except Exception,e:
                print e
                is_success = False

        return is_success

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')
    def post(self, *args, **kwargs):
        obj = MainForm()
        result = obj.check_valid(self)
        print result
        self.write('ok')



settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
    'login_url': '/login'
}

application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
